const log = require('../util/log'),
  urlDao = require('../dao/urlDao'),
  uwDao = require('../dao/urlWordDao'),
  upt = require('../task/updatePTask');

module.exports = (req, res) => {
  require('../util/service').handlePost(req, res, (reqJSON, resolve) => {
    const sUrl = reqJSON.url;
    if (!sUrl) {
      resolve({
        result: -1,
        msg: 'url不能空'
      })
      return
    }
    new Promise(resolve => {
      urlDao.findByUrl(sUrl, url => {
        if (url != null) {
          url.lastVisitedTime = new Date();
          urlDao.update(url, () => {
            resolve(url)
          })
        } else {
          url = {
            url: sUrl,
            p: 0,
            lastVisitedTime: new Date()
          }
          urlDao.insert(url, () => {
            resolve(url)
          })
        }
      })
    }).then(url => {
      if (!req.session.searchWords) {
        resolve({
          result: 1
        })
        return
      }
      const updateUrlWordPromises = []
      req.session.searchWords.forEach(word => {
        updateUrlWordPromises.push(new Promise(resolve => {
          uwDao.findByUrlIdWordId(url.urlId, word.wordId, uw => {
            if (uw != null) {
              upt.add(uw, () => {
                resolve()
              });
            } else {
              uw = {
                urlId: url.urlId,
                wordId: word.wordId,
                p: 0
              }
              uwDao.insert(uw, () => {
                upt.add(uw, () => {
                  resolve()
                })
              })
            }
          })
        }))
      })
      Promise.all(updateUrlWordPromises).then(result => {
        resolve({
          result: 1
        })
      }).catch(err => log(err))
    }).catch(err => log(err))
  })
}
